<template>
    <!-- pages/login/index.wxml -->
    <view class="page">
        <view>
            <image class="imgbg" :src="imgUrl + 'login-bg.png'"></image>
        </view>
        <view class="logintext">
            <text>Hi～意约！请登录</text>
        </view>
        <view class="loginagreement">
            <text>登录即注册表示同意</text>
            <text @tap.stop.prevent="toUseragreement">《用户协议》</text>
            和
            <text @tap.stop.prevent="toPrivacypolicy">《隐私条款》</text>
        </view>
        <view class="inputbox">
            <van-cell-group>
                <view class="loginiput">
                    <van-field label="+86"
                        custom-style=" width: 670rpx;height: 44px;border-radius: 42rpx;margin-bottom: 40rpx;"
                        class="loginiput-phone" title-width="2.2rem" :value="phone" placeholder="| 请输入手机号码"
                        :border="false" @change="onChangePhone" />
                </view>
                <view class="loginiput" v-if="!show">
                    <van-field type="password"
                        custom-style=" width: 670rpx;height: 44px;border-radius: 42rpx;margin-bottom: 40rpx;"
                        :value="password" placeholder="请输入密码" :border="false" @change="onChangePassword" />
                </view>
                <view class="loginiput" v-if="show">
                    <van-field maxlength="6"
                        custom-style=" width: 670rpx;height: 88rpx;border-radius: 42rpx;margin-bottom: 40rpx;"
                        :value="phoneCode" placeholder="请输入验证码" :border="false"
                        @change="onChangeType($event, { type: 'phoneCode' })" data-type="phoneCode">
                        <view v-if="btnvisible == true" class="codebtn" slot="button" @tap.stop.prevent="getCode">获取验证码
                        </view>
                        <button v-if="btnvisible == false" class="codebtn" slot="button" @tap.stop.prevent="getCode"
                            :disabled="true">{{ count_down }}秒</button>
                    </van-field>
                </view>
            </van-cell-group>
            <!-- <view class="page-section">
      <view class="weui-cells weui-cells_after-title">
        <view class="weui-cell weui-cell_input">
          <input class="weui-input loginiput" type="text" maxlength="10" placeholder="   +86              |  请输入手机号码" />
        </view>
      </view>
    </view>
    <view class="page-section">
      <view class="weui-cells weui-cells_after-title">
        <view class="weui-cell weui-cell_input">
          <input class="weui-input loginiput" maxlength="10" placeholder="请输入密码" />
        </view>
      </view>
    </view> -->
        </view>
        <button class="loginbtn" @tap="onLogin">登录</button>
        <view class="verify">
            <text @tap="onTab" v-if="!show">短信验证码登录</text>
            <text @tap="onTab" v-if="show">账号密码登录</text>
            <text @tap="toRegister">忘记密码</text>
        </view>
        <view class="wxbtn">
            <text class="wxbtn">使用第三方账号登录</text>
            <view class="wximgbox" @tap="onWeixin">
                <image class="wximg" :src="imgUrl + 'wxlogo.png'"></image>
            </view>
        </view>
    </view>
</template>

<script>
// pages/login/index.js
const app = getApp(); // 引入app

import _request from '../../utils/request.js';
export default {
    data() {
        return {
            imgUrl: app.globalData.imgUrl,

            //全局img路径
            phone: '',

            password: '',
            show: false,
            btnvisible: true,
            count_down: 60,
            phoneCode: '',
            timer: '',
            newPassword: '',
            crm_password: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) { },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () { },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // wx.hideHomeButton()
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () { },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () { },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () { },
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () { },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () { },
    methods: {
        // 获取验证码
        getCode() {
            _request
                .postObj('/storeSms/getPhoneCode', {
                    mobile: this.phone,
                    type: 2
                })
                .then((res) => {
                    if (res.data.code === 200) {
                        this.get_code_settime();
                    } else if (res.data.code === 408) {
                        uni.showModal({
                            title: '提示',
                            content: res.data.message,
                            confirmText: '我知道了',
                            showCancel: false
                        });
                    } else {
                        uni.showToast({
                            title: res.data.message,
                            icon: 'none',
                            duration: 1000
                        });
                    }
                })
                .catch((error) => {
                    console.log(error, 'error');
                });
        },

        //验证码按钮倒计时方法
        get_code_settime(that) {
            var that = this;
            let countDown = that.data.count_down; //获取倒计时初始值

            that.setData({
                //这里把setInterval复制给变量名timer
                timer: setInterval(function () {
                    // 每隔一秒减1
                    countDown--;
                    that.setData({
                        btnvisible: false,
                        //此处用于隐藏验证码点击按钮，使倒计时显示
                        count_down: countDown //倒计时计数
                    }); //当计数为0时，清空定时器，使验证码按钮再次显示

                    if (countDown == 0) {
                        clearInterval(that.data.timer); //清除timer，

                        that.setData({
                            btnvisible: true,
                            count_down: '60'
                        });
                    }
                }, 1000)
            });
        },

        // 自动绑定推荐人
        onSubmitcode(userId) {
            _request
                .postObj('/recomUser/bindInviteCode', {
                    userId,
                    invitecode: uni.getStorageSync('code')
                })
                .then((res) => {
                    if (res.data.code == 200) {
                        console.log('自动绑定成功', uni.getStorageSync('code'));
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },

        onChangePhone(e) {
            this.setData({
                phone: e.detail.replace(/\s+/g, '')
            });
        },

        onChangePassword(e) {
            this.setData({
                password: e.detail.replace(/\s+/g, '')
            });
        },

        toRegister() {
            uni.navigateTo({
                url: '../register/index'
            });
        },

        // 查看隐私条款
        toPrivacypolicy() {
            uni.navigateTo({
                url: '/pages/aboutus/privacypolicy/index'
            });
        },

        // 查看用户协议
        toUseragreement() {
            uni.navigateTo({
                url: '/pages/aboutus/useragreement/index'
            });
        },

        // 切换方式登录
        onTab() {
            this.setData({
                show: !this.show
            });
        },

        // 获取手机号
        onChangeType(e, _dataset) {
            /* ---处理dataset begin--- */
            this.datasetHandle(e, _dataset);
            /* ---处理dataset end--- */
            const { type } = e.currentTarget.dataset;

            switch (type) {
                case 'phone':
                    this.setData({
                        phone: e.detail.replace(/\s+/g, '')
                    });
                    break;

                case 'newPassword':
                    this.setData({
                        newPassword: e.detail.replace(/\s+/g, '')
                    });
                    break;

                case 'crm_password':
                    this.setData({
                        crm_password: e.detail.replace(/\s+/g, '')
                    });
                    break;

                case 'phoneCode':
                    this.setData({
                        phoneCode: e.detail.replace(/\s+/g, '')
                    });
                    break;

                default:
                    break;
            }
        },

        // 前往登录页
        onLogin() {
            let data = null;

            if (!this.phone) {
                uni.showToast({
                    title: '请输入正确的手机号!',
                    icon: 'none'
                });
                return;
            }

            if (!this.show) {
                if (!this.password) {
                    uni.showToast({
                        title: '请输入密码!',
                        icon: 'none'
                    });
                    return;
                }

                data = {
                    mobile: this.phone,
                    password: this.password,
                    type: 2,
                    client: 'Applet'
                };
            } else {
                if (!this.phoneCode) {
                    uni.showToast({
                        title: '请输入验证码!',
                        icon: 'none'
                    });
                    return;
                }

                data = {
                    mobile: this.phone,
                    phoneCode: this.phoneCode,
                    client: 'Applet'
                };
            }

            _request
                .postObj('/storeUser/login', { ...data })
                .then((res) => {
                    if (res.data.code === 200) {
                        uni.setStorageSync('userid', res.data.data.id);
                        uni.setStorageSync('userId', res.data.data.id);
                        uni.setStorageSync('user', res.data.data);
                        uni.setStorageSync('token', res.data.data.token);
                        uni.setStorageSync('storeId', res.data.data.storeId);
                        this.onSubmitcode(res.data.data.id);
                        uni.redirectTo({
                            // url: '/firstpages/home/index',
                            url: '/firstpages/my2/index'
                        });
                    } else {
                        uni.showToast({
                            title: res.data.message,
                            icon: 'none'
                        });
                    }
                })
                .catch((error) => {
                    console.log(error, 'error');
                });
        },

        //跳转微信登陆
        onWeixin() {
            uni.navigateTo({
                url: '../../firstpages/authorization/index'
            });
        }
    }
};
</script>
<style>
/* pages/login/index.wxss */
page {
    background-color: transparent;
}

.page {
    color: #ffffff;
}

/* 背景图 */
.imgbg {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    height: 100%;
    width: 750rpx;
    z-index: -1;
}

/* 请登录样式 */
.logintext {
    width: 500rpx;
    height: 80rpx;
    font-size: 56rpx;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    position: fixed;
    top: 180rpx;
    left: 80rpx;
}

/* 用户协议样式 */
.loginagreement {
    /* width: 480rpx; */
    height: 34rpx;
    font-size: 24rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    line-height: 34rpx;
    position: fixed;
    top: 280rpx;
    left: 80rpx;
}

/* 表单样式 */
.inputbox {
    position: fixed;
    top: 436rpx;
    left: 40rpx;
}

/deep/.custom-class {
    background: transparent !important;
}

.loginiput {
    width: 670rpx;
    height: 44px;
    background: #ffffff;
    border-radius: 42rpx;
    margin-bottom: 40rpx;
    color: #ffffff;
}

.loginiput-phone /deep/ .van-cell__title {
    flex: none !important;
}

.weui-cell>text {
    position: relative;
    top: 64rpx;
    left: 40rpx;
}

.loginbtn {
    width: 670rpx;
    height: 88rpx;
    background: #ffffff;
    box-shadow: 0px 2px 4px 0px #ff8722;
    border-radius: 42rpx;
    position: fixed;
    top: 720rpx;
    left: 40rpx;
    color: #ff8722;
}

/* 信息验证和忘记样式 */
.verify {
    width: 600rpx;
    height: 34rpx;
    font-size: 24rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #ffffff;
    line-height: 34rpx;
    position: fixed;
    top: 830rpx;
    left: 80rpx;
    display: flex;
    justify-content: space-between;
}

/* 第三方样式 */
.wxbtn {
    position: fixed;
    top: 1000rpx;
    left: 256rpx;
}

.wxbtn {
    width: 252rpx;
    height: 40rpx;
    font-size: 28rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #ffffff;
    line-height: 40rpx;
}

.wximgbox {
    margin-left: 86rpx;
    margin-top: 100rpx;
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    border: 1px solid #ffffff;
    text-align: center;
    line-height: 105rpx;
}

.wximg {
    width: 50rpx;
    height: 50rpx;
}

.codebtn {
    height: 40rpx;
    font-size: 28rpx;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #000;
    line-height: 40rpx;
    color: #999;
    /* background-color: #FFFFFF;
  border-color: #FFFFFF; */
}

/* 组件样式修改 */
</style>
